package org.melord.cap;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

public class HttpRequestParser {
	public static final int CR = '\r';
	public static final int LF = '\n';
	HttpRequest request = new HttpRequest();

	public HttpRequest parser(InputStream in) throws IOException {
		DataInputStream dis = null;
		if (in instanceof DataInputStream) {
			dis = (DataInputStream) in;
		} else {
			dis = new DataInputStream(in);
		}
		parseHeader(dis);
		// parseBody(dis);
		dis.close();
		return request;
	}

	protected void parseHeader(DataInputStream dis) throws IOException {
		StringBuilder sb = new StringBuilder();
		boolean cr = false;
		boolean lf = false;
		int crlf = 0;
		char ch = (char) dis.read();
		while (ch >= 0) {
			if (ch == CR) {
				cr = true;
			} else if (ch == LF) {
				lf = true;
				if (cr) {
					crlf++;
				}
				if (crlf > 1) {
					break;
				} else {
					String s = sb.toString();
					sb.delete(0, sb.length());
					parseLine(s);
				}
			} else {
				if (!(cr && lf)) {
					if (cr) {
						sb.append(cr);
					} else if (lf) {
						sb.append(lf);
					}
				}
				cr = false;
				lf = false;
				crlf = 0;
				sb.append(ch);
			}
			ch = (char) dis.read();
		}
	}

	private void parseVersion(String s) {
		int index = s.indexOf("HTTP");
		String uri = s.substring(request.getMethod().length(), index).trim();
		request.setRequestURI(uri);

		String protocol = s.substring(index);
		request.setProtocol(protocol);
	}

	private void parseLine(String s) {
		if (s.startsWith("GET")) {
			String method = "GET";
			request.setMethod(method);
			parseVersion(s);
		} else if (s.startsWith("POST")) {
			String method = "POST";
			request.setMethod(method);
			parseVersion(s);
		}  else {
			int pos = s.indexOf(": ");
			if (pos > 0) {
				String name = s.substring(0, pos);
				String value = s.substring(pos + 2);
				request.addHeader(name, value);
			}
		}
	}

	public HttpRequest getRequest() {
		return request;
	}
}
